package com.roc.service.impl.profit;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.DaoException;
import com.roc.dao.agent.IAgentInfoDao;
import com.roc.dao.profit.IProfitDao;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitDetail;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.ProfitRule;
import com.roc.service.ServiceException;
import com.roc.service.profit.IProfitService;
import com.roc.util.AmtUtil;
import com.roc.util.constant.Constant;
@Service
@Transactional
public class ProfitServiceImpl implements IProfitService {
	private Logger logger=LogManager.getLogger(ProfitServiceImpl.class);

	@Autowired
	private IProfitDao profitDao;
	
	@Autowired
	private IAgentInfoDao agentInfoDao;
	
	
	
 	public Operators loadById(long id) throws ServiceException{
 		Operators operators=null;
		try{
			 operators=(Operators) profitDao.loadById(id, Operators.class);
		}catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询代理商信息出错！");
		}
		return operators;
	}
	
	@Override
	public Map getOpertorsIdsTreeById(Long id) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getOpertorsIdsTreeById(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有代理商ID和名字信息出错！");
		}
		return map;
	}
	@Override
	public Map getDirectlyAgentIdsTreeBySuperId(Long id) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getDirectlyAgentIdsBySuperId(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有直属代理商ID和名字信息出错！");
		}
		return map;
	}
	@Override
	public String getOpertorsIdsById(Long id) throws ServiceException {
		StringBuffer sb = new StringBuffer();
		String str="";
		sb.append("(");
		try{
		List list = profitDao.getOpertorsIdsTreeById(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				sb.append(obj[0]+",");
			}
			
			str=sb.substring(0, sb.length()-1)+")";
		}
	
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有代理商ID信息出错！");
		}
		return str;
	}
	@Override
	public String getDirectlyAgentIdsBySuperId(Long id) throws ServiceException {
		StringBuffer sb = new StringBuffer();
		String str="";
		sb.append("(");
		try{
		List list = profitDao.getDirectlyAgentIdsBySuperId(id);
		if(list.size()>0){
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				sb.append(obj[0]+",");
			}
			str=sb.substring(0, sb.length()-1)+")";
		}else{
			str=sb.append(" 0 )").toString();
		}
		
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有直属代理商ID信息出错！");
		}
		return str;
	}

	
	public Map<String,BigDecimal> queryProfitRule(String accountNo) throws ServiceException {
		
		Map<String,BigDecimal> map= new HashMap<String,BigDecimal>();
		try{
			 List<ProfitRule> profitRuleList= profitDao.queryProfitRule(accountNo);
			 for( int i=0;i<profitRuleList.size();i++){
				 ProfitRule profitRule= profitRuleList.get(i);
				 if("01".equals(profitRule.getMccTypeCode())){
					 map.put("0100", AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					 map.put("0101", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
					 map.put("0199", new BigDecimal(profitRule.getMaxFee()));
				 }else if ("04".equals(profitRule.getMccTypeCode())){
					 map.put("0400",AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					 map.put("0401", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
					 map.put("0499", new BigDecimal(profitRule.getMaxFee()));
				 }else if("05".equals(profitRule.getMccTypeCode())){
					 map.put("0500",AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					 map.put("0501", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
				 }else if("06".equals(profitRule.getMccTypeCode())){
					 map.put("0600",AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					// map.put("0601", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
				 }else if("07".equals(profitRule.getMccTypeCode())){
					 map.put("0700",AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					// map.put("0701", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
				 }else if("08".equals(profitRule.getMccTypeCode())){
					 map.put("0800",AmtUtil.divide(profitRule.getProfitFee(), 100));//借记卡
					// map.put("0801", AmtUtil.divide(profitRule.getProfitSettleRate(), 100));//信用卡
				 }
				 
			 }
			}
			catch(DaoException e){
				logger.debug(e.getMessage());
				throw new ServiceException("查询操作员accountNo对应代理商分润规则信息出错！");
			}
			
		return map;
	}
	
	/**
	 * 获取分润比例
	 * 
	 * @param agentId
	 * @param transAmount
	 * @return
	 */
	public String getProfitPercent(String accountNo , BigDecimal transAmount) throws ServiceException {
		logger.info("生产分润确认函时获取分润百分比传入参数accountNo =" + accountNo);
		try {
			List<ProfitPercent> percentList = agentInfoDao.queryProfitPer(accountNo);
			if (percentList == null || percentList.size() == 0) {// 未配置则使用默认值
				percentList = getDefPer();
				// log.info("代理商:[" + agentId + "]采用默认分润比例");
			}

			for (ProfitPercent profitPercent : percentList) {
				String isEnd = profitPercent.getIs_end();
				BigDecimal maxAmt = profitPercent.getMax_amt();
				if ("0".equals(isEnd)) {// 左区间
					if (maxAmt.compareTo(transAmount) == 1) {
						return profitPercent.getPercent();
					}
				} else if ("1".equals(isEnd)) {// 区间中
					if (transAmount.compareTo(maxAmt) == 1) {
						continue;
					}
					return profitPercent.getPercent();

				} else if ("2".equals(isEnd)) {// 右区间
					return profitPercent.getPercent();
				}
			}
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			logger.info("获取分润百分比异常 DaoException ：" +e);
			throw new ServiceException("获取分润百分比信息出错！");
		}
		return "1";//默认是百分百

	}
	
	/**
	 * 获取默认的分润比例集合
	 * 
	 * @return
	 */
	private  List<ProfitPercent> getDefPer() {

		List<ProfitPercent> percentList = new ArrayList<ProfitPercent>();
		for (int i = 0; i < Constant.DEFPER.length; i++) {
			String isEnd = Constant.DEFPER[i][0];
			BigDecimal amt = new BigDecimal(Constant.DEFPER[i][1]);
			ProfitPercent p = new ProfitPercent();
			p.setIs_end(isEnd);
			if ("2".equals(isEnd)) {// 右区间
				p.setLimit_amt(amt);
			} else {
				p.setMax_amt(amt);
			}
			p.setPercent(Constant.DEFPER[i][2]);
			percentList.add(p);
		}

		return percentList;
	}

	@Override
	public Operators getOpertorsByAccountNo(String accountNo)
			throws ServiceException {
		Operators operators = null;
		try {
			operators=profitDao.getOpertorsByAccountNo(accountNo);
		}catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询代理商不唯一！");
			}
		return operators;
	}

	@Override
	public Map getDirectlyAgentIdsTreeByRealId(Long id) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getDirectlyAgentIdsTreeByRealId(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有代理商ID和名字信息出错！");
		}
		return map;
	}

	@Override
	public String getOpertorsScIdById(Long id) throws ServiceException {
		StringBuffer sb = new StringBuffer();
		String str="";
		sb.append("(");
		try{
		List list = profitDao.getDirectlyAgentIdsTreeByRealId(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				sb.append(obj[0]+",");
			}
			
			str=sb.substring(0, sb.length()-1)+")";
		}
	
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有代理商ID信息出错！");
		}
		return str;
	}
	
	//查询云商宝代理商
	@Override
	public Map getYsbOpertorsIdsTreeById(Long id,String roleType) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getYsbOpertorsIdsTreeById(id,roleType);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有代理商ID和名字信息出错！");
		}
		return map;
	}
	/*
	 * 云商宝直属和自己*/
	@Override  
	public Map getYsbDirectlyAgentIdsTreeBySuperId(Long id) throws ServiceException {
		Map map=new HashMap();
		try{
		List list = profitDao.getYsbDirectlyAgentIdsBySuperId(id);
			Iterator iterator=list.iterator();
			while(iterator.hasNext()){
				Object[] obj=(Object[]) iterator.next();
				map.put(obj[0], obj[1]);
			}
		}
		catch(DaoException e){
			logger.debug(e.getMessage());
			throw new ServiceException("查询操作员ID下面的所有直属代理商ID和名字信息出错！");
		}
		return map;
	}
	
}
